<?php
/**
 * 对数组进行转码
 * @param array
 * @return array
 */
function toGB2312( $a )
{
	if ( is_array($a) )
	{
		array_map( "toGB2312", $a );
	}
	else
	{
		UTF8toGB2312($a);
	}
	return $a;
}

function toUTF8( $a )
{
	if ( is_array($a) )
	{
		array_map( "toUTF8", $a );
	}
	else
	{
		GB2312toUTF8($a);
	}
	return $a;
}

// 中文字符转码
function UTF8toGB2312($str)
{
	return iconv("utf-8","gb2312",$str);
}


function GB2312toUTF8($str)
{
	return iconv("gb2312","utf-8",$str);
}


/**
 * 按指定的长度切割字符串
 *
 * @param  string   $string  需要切割的字符串
 * @param  integer  $length  长度
 * @param  string   $dot     切割后补充的字符串
 * @return string
*/
function csubstr($string, $length, $dot = '')
{
    if (strlen($string) <= $length){
        return $string;
      }
    $n = $tn = $noc = 0;
    while ($n < strlen($string)) {
        $t = ord($string[$n]);
        if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
            $tn = 1; $n++; $noc++;
        } elseif (194 <= $t && $t <= 223) {
            $tn = 2; $n += 2; $noc += 2;
        } elseif (224 <= $t && $t < 239) {
            $tn = 3; $n += 3; $noc += 2;
        } elseif (240 <= $t && $t <= 247) {
            $tn = 4; $n += 4; $noc += 2;
        } elseif (248 <= $t && $t <= 251) {
            $tn = 5; $n += 5; $noc += 2;
        } elseif ($t == 252 || $t == 253) {
            $tn = 6; $n += 6; $noc += 2;
        } else {
            $n++;
        }
        if ($noc >= $length)
            break;
    }
    $noc > $length && $n -= $tn;
    return substr($string, 0, $n) . $dot;
}

/**
 * 从数组中删除空白的元素（包括只有空白字符的元素）
 *
 * @param array $arr
 * @param boolean $trim
 */
function array_remove_empty($arr, $trim = true)
{
    foreach ($arr as $key => $value) {
        if (is_array($value)) {
            array_remove_empty($arr[$key]);
        } else {
            $value = trim($value);
            if ($value == '') {
                unset($arr[$key]);
            } elseif ($trim) {
                $arr[$key] = $value;
            }
        }
    }
    return $arr;
}


/*
 * 加密，可逆
 * 可接受任何字符
 * 安全度非常高
 */
function encrypt($txt, $key)
{
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $nh1 = rand(0,64);
    $nh2 = rand(0,64);
    $nh3 = rand(0,64);
    $ch1 = $chars{$nh1};
    $ch2 = $chars{$nh2};
    $ch3 = $chars{$nh3};
    $nhnum = $nh1 + $nh2 + $nh3;
    $knum = 0;$i = 0;
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
    $txt = base64_encode($txt);
    $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
    $tmp = '';
    $j=0;$k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
        $tmp .= $chars{$j};
    }
    $tmplen = strlen($tmp);
    $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
    $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
    return $tmp;
}

/*
 * 解密
 * 
 */
 function decrypt($txt, $key)
 {
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
    $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
    $knum = 0;$i = 0;
    $tlen = strlen($txt);
    while(isset($key{$i})) $knum +=ord($key{$i++});
    $ch1 = $txt{$knum % $tlen};
    $nh1 = strpos($chars,$ch1); 
    $txt = substr_replace($txt,'',$knum % $tlen--,1);
    $ch2 = $txt{$nh1 % $tlen};
    $nh2 = strpos($chars,$ch2);
    $txt = substr_replace($txt,'',$nh1 % $tlen--,1);
    $ch3 = $txt{$nh2 % $tlen};
    $nh3 = strpos($chars,$ch3);
    $txt = substr_replace($txt,'',$nh2 % $tlen--,1);
    $nhnum = $nh1 + $nh2 + $nh3;
    $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
    $tmp = '';
    $j=0; $k = 0;
    $tlen = strlen($txt);
    $klen = strlen($mdKey);
    for ($i=0; $i<$tlen; $i++) {
        $k = $k == $klen ? 0 : $k;
        $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
        while ($j<0) $j+=64;
        $tmp .= $chars{$j};
    }
    $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
    return base64_decode($tmp);
}

//下载文件
function down($filePath,$fileName)
{
	if(file_exists($filePath)){
			//如果文件存在 下载
			header("Content-Type: application/octet-stream");
      $filename = '"' . htmlspecialchars($fileName) . '"';
      $filesize = filesize($filePath);
      $charset = 'UTF-8';
      header("Content-Disposition: attachment; filename={$filename}; charset={$charset}");
      header('Pragma: cache');
      header('Cache-Control: public, must-revalidate, max-age=0');
      header("Content-Length: {$filesize}");
      Header("Accept-Ranges: bytes");  
      readfile($filePath);
      exit;
	}else{
			alert('文件不存在！');
	}
}

/**
 *PHP模拟JS alert
 *@param string $msg 提示信息
 *@param integer $url 跳转路径
 */
function alert($msg,$url='')
{
	//强制编码，防止乱码
	header("Content-type: text/html; charset=utf-8");
	$html= "<script type='text/javascript'>alert('".$msg."');";
	if($url==''){
		$html .= "history.back();";
	}else{
		$html .= "location.href='".$url."';";
	}
	$html .="</script>";
	echo $html;
	exit;
}


//取文件后缀名
function getExt($filename)
{
	$arr=explode('.',$filename);
	$ext=strtolower(end($arr));
	return $ext;
}

/**
 * 获取客户端IP
 * @return string
 */
function getIP()
{
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
       $ip = getenv("HTTP_CLIENT_IP");
   }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
       $ip = getenv("REMOTE_ADDR");
   }else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
       $ip = $_SERVER['REMOTE_ADDR'];
   }else{
       $ip = "unknown";
   }
   return $ip;
}

?>